package com.xzz.finger;

import java.util.Arrays;

/**
 * @author: hhz
 * @create: 2022-02-21 16:27
 * 剑指 Offer 29. 顺时针打印矩阵
 **/
public class SpiralOrder {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}})));
    }
    public static int[] spiralOrder(int[][] matrix) {
        if(matrix.length==0){
            return new int[0];
        }
        int m = matrix.length;
        int n = matrix[0].length;
        int up = 0;
        int low = m-1;
        int left = 0;
        int right = n-1;
        int[] res = new int[m*n];
        int i = 0;
        while (i<m*n){
            if(up<=low){
                for (int j = left; j <= right; j++) {
                    res[i++] = matrix[up][j];
                }
                up++;
            }
            if(left<=right){
                for (int j = up; j <= low; j++) {
                    res[i++] = matrix[j][right];
                }
                right--;
            }
            if(up<=low){
                for (int j = right; j >= left; j--) {
                    res[i++] = matrix[low][j];
                }
                low--;
            }
            if(left<=right){
                for (int j = low; j >= up; j--) {
                    res[i++] = matrix[j][left];
                }
                left++;
            }
        }
        return res;
    }
}
